package cn.deschen.search.index.adUnitEle.adUnitKeyword;

import cn.deschen.search.index.Many2ManyIndexAware;
import lombok.EqualsAndHashCode;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author hanbin_chen
 * @Description 关键词单元索引，四级索引
 * @DateTime 2021/6/7
 * @Version V1.0.0
 */
@Component
@EqualsAndHashCode
public class AdUnitKeywordIndex extends Many2ManyIndexAware<Long, Long, Long, AdUnitKeywordObject> {

    public static final Map<Long, AdUnitKeywordObject> storageMap = new ConcurrentHashMap<>();

    /**
     * 映射：推广单元Id -> 关键词ID集合
     */
    public static final Map<Long, Set<Long>> unitKeywordMap = new ConcurrentHashMap<>();

    /**
     * 映射： 关键词ID -> 推广单元Id集合
     */
    public static final Map<Long, Set<Long>> keywordUnitMap = new ConcurrentHashMap<>();

    public AdUnitKeywordIndex() {
        super(storageMap, unitKeywordMap, keywordUnitMap);
    }


    /**
     * 推广单元ID
     * @param value
     * @return
     */
    @Override
    public Long getAId(AdUnitKeywordObject value) {
        return value.getUnitId();
    }

    /**
     * 关键词ID
     * @param value
     * @return
     */
    @Override
    public Long getBId(AdUnitKeywordObject value) {
        return value.getKeywordId();
    }

    public Set<Long> matchKeyword(Collection<Long> unitIdList, List<Long> keywordKeyList) {
        if (CollectionUtils.isEmpty(keywordKeyList)) {
            return Collections.emptySet();
        }
        return unitIdList.stream().filter(unitId -> unitKeywordMap.get(unitId).containsAll(keywordKeyList)).collect(Collectors.toSet());
    }
}
